package service

import (
	"context"
	pb "doctor-srv/basic/proto"
	"doctor-srv/basic/config"
	"doctor-srv/handler/model"
	"fmt"
	"strings"
	"time"
)

type ConsultationService struct {
	pb.UnimplementedConsultationServer
}

// GenerateOrderNo 生成订单号
func GenerateOrderNo(prefix string) string {
	return fmt.Sprintf("%s%d", prefix, time.Now().UnixNano())
}

// CreateConsultation 创建问诊订单
func (s *ConsultationService) CreateConsultation(ctx context.Context, req *pb.CreateConsultationReq) (*pb.CreateConsultationResp, error) {
	consultation := model.Consultation{
		OrderNo:            GenerateOrderNo("CON"),
		PatientID:          req.PatientId,
		DoctorID:           req.DoctorId,
		ConsultationType:   int(req.ConsultationType),
		SymptomDescription: req.SymptomDescription,
		AttachmentUrls:     strings.Join(req.AttachmentUrls, ","),
		Status:             0, // 待接诊
	}

	if err := consultation.CreateConsultation(config.DB); err != nil {
		return nil, err
	}

	return &pb.CreateConsultationResp{
		ConsultationId: int64(consultation.ID),
		OrderNo:        consultation.OrderNo,
	}, nil
}

// GetConsultationDetail 获取问诊详情
func (s *ConsultationService) GetConsultationDetail(ctx context.Context, req *pb.GetConsultationDetailReq) (*pb.GetConsultationDetailResp, error) {
	var consultation model.Consultation
	err := consultation.GetConsultationByID(config.DB, req.ConsultationId)
	if err != nil {
		return nil, err
	}

	// 获取患者和医生信息
	var patient model.Patient
	var doctor model.Doctor
	patient.GetPatientByID(config.DB, consultation.PatientID)
	doctor.GetDoctorByID(config.DB, consultation.DoctorID)

	return &pb.GetConsultationDetailResp{
		Consultation: &pb.ConsultationInfo{
			ConsultationId:      int64(consultation.ID),
			OrderNo:             consultation.OrderNo,
			PatientId:           consultation.PatientID,
			PatientName:         patient.Name,
			DoctorId:            consultation.DoctorID,
			DoctorName:          doctor.Name,
			ConsultationType:    int32(consultation.ConsultationType),
			SymptomDescription:  consultation.SymptomDescription,
			Status:              int32(consultation.Status),
			CreatedAt:           consultation.CreatedAt.Unix(),
		},
	}, nil
}

// UpdateConsultationStatus 更新问诊状态
func (s *ConsultationService) UpdateConsultationStatus(ctx context.Context, req *pb.UpdateConsultationStatusReq) (*pb.UpdateConsultationStatusResp, error) {
	var consultation model.Consultation
	err := consultation.GetConsultationByID(config.DB, req.ConsultationId)
	if err != nil {
		return &pb.UpdateConsultationStatusResp{
			Success: false,
			Message: "问诊不存在",
		}, err
	}

	consultation.Status = int(req.Status)
	
	if req.Status == 1 {
		// 开始问诊
		consultation.StartTime = time.Now()
	} else if req.Status == 2 || req.Status == 3 {
		// 结束或取消
		consultation.EndTime = time.Now()
	}

	if err := consultation.UpdateConsultation(config.DB); err != nil {
		return &pb.UpdateConsultationStatusResp{
			Success: false,
			Message: "更新失败",
		}, err
	}

	return &pb.UpdateConsultationStatusResp{
		Success: true,
		Message: "更新成功",
	}, nil
}

// GetConsultationList 获取问诊列表
func (s *ConsultationService) GetConsultationList(ctx context.Context, req *pb.GetConsultationListReq) (*pb.GetConsultationListResp, error) {
	consultations, total, err := model.GetConsultationList(config.DB, req.UserId, int(req.UserType), int(req.Page), int(req.PageSize))
	if err != nil {
		return nil, err
	}

	var consultationInfos []*pb.ConsultationInfo
	for _, consultation := range consultations {
		// 获取患者和医生信息
		var patient model.Patient
		var doctor model.Doctor
		patient.GetPatientByID(config.DB, consultation.PatientID)
		doctor.GetDoctorByID(config.DB, consultation.DoctorID)

		consultationInfos = append(consultationInfos, &pb.ConsultationInfo{
			ConsultationId:     int64(consultation.ID),
			OrderNo:            consultation.OrderNo,
			PatientId:          consultation.PatientID,
			PatientName:        patient.Name,
			DoctorId:           consultation.DoctorID,
			DoctorName:         doctor.Name,
			ConsultationType:   int32(consultation.ConsultationType),
			SymptomDescription: consultation.SymptomDescription,
			Status:             int32(consultation.Status),
			CreatedAt:          consultation.CreatedAt.Unix(),
		})
	}

	return &pb.GetConsultationListResp{
		Consultations: consultationInfos,
		Total:         total,
	}, nil
}

// RateConsultation 评价问诊
func (s *ConsultationService) RateConsultation(ctx context.Context, req *pb.RateConsultationReq) (*pb.RateConsultationResp, error) {
	rating := model.ConsultationRating{
		ConsultationID: req.ConsultationId,
		Rating:         int(req.Rating),
		Comment:        req.Comment,
	}

	if err := rating.CreateConsultationRating(config.DB); err != nil {
		return &pb.RateConsultationResp{
			Success: false,
			Message: "评价失败",
		}, err
	}

	return &pb.RateConsultationResp{
		Success: true,
		Message: "评价成功",
	}, nil
}

